package com.google.mlkit.samples.nl.translate;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopyHelper {
    public static final int STORAGE_PERMISSION_CODE = 100;

    public static boolean checkStoragePermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 使用新的存储权限模型
            return Environment.isExternalStorageManager();
        } else {
            // Android 10 及以下
            return ContextCompat.checkSelfPermission(activity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
    }

    public static void requestStoragePermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
            intent.setData(uri);
            activity.startActivity(intent);
        } else {
            ActivityCompat.requestPermissions(activity,
                    new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    },
                    STORAGE_PERMISSION_CODE);
        }
    }

    /**
     * 复制内部数据目录到外部数据目录
     */
    public static boolean copyInternalToExternal(Context context, String internalPath, String externalPath) {
        File internalDir = new File(context.getFilesDir().getParent(), internalPath);
        File externalDir = new File(context.getExternalFilesDir(null).getParent(), externalPath);

        if (!internalDir.exists()) {
            Log.e("FileCopy", "Internal directory doesn't exist: " + internalDir.getAbsolutePath());
            return false;
        }

        if (!externalDir.exists()) {
            if (!externalDir.mkdirs()) {
                Log.e("FileCopy", "Failed to create external directory: " + externalDir.getAbsolutePath());
                return false;
            }
        }

        return copyDirectory(internalDir, externalDir);
    }

    /**
     * 递归复制目录
     */
    private static boolean copyDirectory(File sourceDir, File targetDir) {
        if (!sourceDir.isDirectory()) {
            return false;
        }

        try {
            File[] files = sourceDir.listFiles();
            if (files == null) return false;

            for (File file : files) {
                File targetFile = new File(targetDir, file.getName());

                if (file.isDirectory()) {
                    if (!targetFile.exists() && !targetFile.mkdirs()) {
                        return false;
                    }
                    copyDirectory(file, targetFile);
                } else {
                    copyFile(file, targetFile);
                }
            }
            return true;
        } catch (Exception e) {
            Log.e("FileCopy", "Error copying directory", e);
            return false;
        }
    }

    /**
     * 复制单个文件
     */
    private static void copyFile(File sourceFile, File destFile) {
        try (InputStream in = new FileInputStream(sourceFile);
             OutputStream out = new FileOutputStream(destFile)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        } catch (IOException e) {
            Log.e("FileCopy", "Error copying file: " + sourceFile.getName(), e);
        }
    }

}